import { query as queryUsers, queryCurrent, queryReplyCount } from '@/services/user';
import { Effect, Reducer } from 'umi';

export interface CurrentUser {
  avatar?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  unreadCount?: number;

  name?: string;
  pid?: string;
  phone?: string;
  token?: string;
  replyCount?: string;
}

export interface UserModelState {
  currentUser?: CurrentUser;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchCurrent({ payload }, { call, put }) {
      const { code, data } = yield call(queryCurrent, payload);

      if (code) {
        // message.info('登录失效，请重新登录')
        return;
      }

      console.log('payload.pid', data.pid);

      const replyCount = yield call(queryReplyCount, data.pid);
      console.log('replyCount', replyCount);

      // yield put({
      //   type:'fetchReplyCount',
      //   payload:data
      // })

      data.replyCount = replyCount.data;
      yield put({
        type: 'saveCurrentUser',
        payload: data,
      });
    },
    *fetchReplyCount({ payload: { pid } }, { call, put }) {
      const { code, data } = yield call(queryReplyCount, pid);
      yield console.log('code', code);
      yield put({
        type: 'saveReplyCount',
        payload: { replyCount: data },
      });
    },
  },

  reducers: {
    clearCurrentUser(state) {
      return {
        ...state,
        currentUser: {},
      };
    },
    saveCurrentUser(state, { payload, payload: { partjobrealname } }) {
      return {
        ...state,
        currentUser: { ...payload, ...{ name: partjobrealname } } || {},
      };
    },
    saveReplyCount(state, { payload }) {
      return {
        ...state,
        currentUser: { ...state.currentUser, ...payload } || {},
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
